package com.peng.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.peng.constant.Constants;
import com.peng.mapper.TMinioMapper;
import com.peng.model.TMinio;
import com.peng.model.TUser;
import com.peng.model.TUserDetailsImpl;
import com.peng.result.R;
import com.peng.util.JWTUtils;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.http.Method;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.awt.*;
import java.util.Objects;

@RestController
public class MinioController {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private TMinioMapper tMinioMapper;

    //为用户添加头像
    @PostMapping(value="/api/user/image")
    public R image(@RequestParam(value = "file") MultipartFile file, @RequestParam(value="id")Integer id ,@RequestHeader(value = "Authorization") String token) throws Exception{

        Integer user_id = JWTUtils.parseUserFromJWT(token).getId();

        minioClient.putObject(PutObjectArgs.builder()
                .bucket(Constants.MINIO_BUCKET_NAME)
                .object("dlyk_image_user_id=" + user_id + ".jpg")
                .stream(file.getInputStream(),
                        file.getSize(),
                        -1)
                .build());

        TMinio tMinio = new TMinio();

        tMinio.setUser_id(user_id);
        tMinio.setBucket(Constants.MINIO_BUCKET_NAME);
        tMinio.setObject("dlyk_image_user_id=" + user_id + ".jpg");

        if(tMinioMapper.selectById(user_id) == null)tMinioMapper.insert(tMinio);
        return R.OK();
    }



    //获得当前用户头像
    @GetMapping(value="/api/userImage")
    public R userImage(Authentication authentication) throws Exception {
        TUserDetailsImpl tUserDetailsImpl = (TUserDetailsImpl)authentication.getPrincipal();

        LambdaQueryWrapper<TMinio> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TMinio::getUser_id,tUserDetailsImpl.getId());

        TMinio userMinio = tMinioMapper.selectOne(queryWrapper);
        String userBucket;
        String userObject;

        if(!Objects.isNull(userMinio)){
            userBucket = userMinio.getBucket();
            userObject = userMinio.getObject();
        } else {
            userBucket = Constants.MINIO_BUCKET_NAME;
            userObject = "baseImage.jpg";
        }
        String url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                .method(Method.GET)
                .bucket(userBucket)
                .object(userObject)
                .build());
        System.out.println(url);
        return R.OK(url);
    }
}
